﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Nissen_Model;
using PosHacker;
using PosHacker.Form;
using System.Threading;

namespace Nissen_Marking.Forms
{
    public partial class FormPartrailQuestion : Form
    {
        public bool CheckBoxAutoNext { get; set; }
        public int BrowserWindowPosition { get; set; }
        public int FormsCount { get; set; }
        public FormTestNames vParentForm { get; set; }

        public string[] ScoringNos { get; set; }

        public static bool isGroupSubmit = false;

        private POSHacker vPOSHacker;

        private FormBrowser vFormBrowser = null;
        private List<FormBrowser> lFB;
        private List<FormSetScoringNo> lFSSN;

        private List<int> lViewSelected;

        private int _MaxWindows = 1;//5

        public FormPartrailQuestion()
        {
            InitializeComponent();
            
        }
        public FormPartrailQuestion(FormBrowser vFormBrowser)
        {
            InitializeComponent();
            this.vFormBrowser = vFormBrowser;
        }
        
        private void FormPartrailQuestion_Load(object sender, EventArgs e)
        {
            this.label1.Text = Nissen_Common.ContextManager.Instance._ContextProperties.TestName;
            this.label2.Text = Nissen_Common.ContextManager.Instance._FormSetCourse.subjectCourseNm;
        }

        private bool isCourseActive(FormSetCourse SelectFormSetCourse)
        {
            IList<SubjectCourse> subjectCourses = new TestNamesService().GetSubjectCourses(SelectFormSetCourse.testExecId);

            if (subjectCourses.Count == 0)
                return true;


            foreach (var subjectCourse in subjectCourses)
            {
                if (SelectFormSetCourse.subjectCourseTestId.Equals(subjectCourse.SubjectCourseID)
                    && SelectFormSetCourse.pageNum.Equals(subjectCourse.SubjectCoursePage))
                {
                    return true;
                }
            }

            return false;

        }

        private bool isTestActive(FormSetCourse SelectFormSetCourse)
        {

            IList<Test> dbTests = new TestNamesService().GetDisplayTests();

            foreach (var dbTest in dbTests)
            {
                if (SelectFormSetCourse.testExecId.Equals(dbTest.TestId))
                {
                    return true;
                }
            }

            return false;
        }

        private void Init() {

            FormSetCourse SelectFormSetCourse = Nissen_Common.ContextManager.Instance._FormSetCourse;
            if (!this.isTestActive(SelectFormSetCourse)
                || !this.isCourseActive(SelectFormSetCourse))
            {

                MessageBox.Show("该科目已被关闭，请重新选择！");
                //this.DialogResult = DialogResult.Abort;
                this.Close();

                return;
            }
            
            this.ScoringNos = null;

            this.Enabled = true;
            for (int i = 0; i < this.FormsCount;i++)
            {
                this.lFB[i].Close();
            }

            this.buttonMark.Enabled = false;

            //POSHacker
            this.vPOSHacker = POSHacker.GetInstance();

            lFSSN =
            this.vPOSHacker.GetMarkableQuestionsList(); //step 1

            if (lFSSN == null)
            {
                this.dataGridView1.DataSource = 0;
                return;
            }

            PartrailQuestionService partrailQuestionService = new PartrailQuestionService();

            
            IList<MarkableQuestion> dbMarkableQuestions = partrailQuestionService.GetMarkableQuestions(SelectFormSetCourse.subjectCourseTestId, SelectFormSetCourse.pageNum);
            IList<FormSetScoringNo> formSetScoringNoes = new List<FormSetScoringNo>();

            bool tmpCheck = false;
            foreach (var formSetScoringNo in lFSSN)
            {
                //Check Multi Windows
                if (this.vFormBrowser != null)
                {
                    foreach (string window_scoringNo in this.vFormBrowser.MainForm.ScoringNos)
                    {
                        if (window_scoringNo != null
                            && window_scoringNo.Equals(formSetScoringNo.scoringNo))
                        {
                            tmpCheck = true;
                            break;
                        }
                    }

                    if(tmpCheck){
                        tmpCheck= false;
                        continue;
                    }
                    
                }

                //Check Manage
                if (dbMarkableQuestions.Count == 0){
                    formSetScoringNoes.Add(formSetScoringNo);
                }else{
                    foreach (var dbMarkableQuestion in dbMarkableQuestions)
                    {
                        if (formSetScoringNo.scoringNo == dbMarkableQuestion.MarkID)
                        {
                                formSetScoringNoes.Add(formSetScoringNo);
                                break;
                        }
                    }
                }
            }

            lFSSN = (List<FormSetScoringNo>)formSetScoringNoes;

            this.dataGridView1.DataSource = lFSSN;
            

             //this.webBrowser1.DocumentText = "<img src=\"" 
             //    + @"http://pos.toshin.com/MarkingSystemWeb/displayImage.do?imageType=correctImg"
             //    + "\"  />";

            this.webBrowser1.Navigate(Application.StartupPath + "\\AnswerDisplay.htm");
            //this.webBrowser1.Navigate(@"http://pos.toshin.com/MarkingSystemWeb/displayImage.do?imageType=correctImg");
            //this.webBrowser1.Url = new Uri(@"http://pos.toshin.com/MarkingSystemWeb/displayImage.do?imageType=correctImg");//2012.04.11 pcj

            //this.webBrowser1.
        }

        public delegate void DG();
        public delegate void DGS(int i,int tmpCount);

        private void CheckBrowser(){
            
            int tmpCount = 1;
            this.lFB = new List<FormBrowser>();
            DG vdg;
            DGS vdgs = new DGS(FormsDo);
            this.FormsCount = lViewSelected.Count;
            
            if (this.FormsCount > this._MaxWindows)
                this.FormsCount = this._MaxWindows;

            this.ScoringNos = new string[this._MaxWindows];
            foreach (int i in lViewSelected) 
            {
                //Max = 5
                if (tmpCount > this._MaxWindows)
                    break;

                while (FormPartrailQuestion.isGroupSubmit)
                {
                    Thread.Sleep(500);
                }

                FormPartrailQuestion.isGroupSubmit = true;

                object[] obj=
                new object[] { i, tmpCount };
                this.Invoke(vdgs, obj);
                tmpCount++;
            }

            while (FormPartrailQuestion.isGroupSubmit)
            {
                Thread.Sleep(500);
            }

            vdg = new DG(FormsGo);
            this.Invoke(vdg);
        }
        private void FormsDo(int i, int tmpCount)
        {
            FormBrowser _vFormBrowser;

            lFSSN[i].numberOfSet = this.textBox1.Text;
            lFSSN[i].mouseMarker = "2";

            _vFormBrowser = new FormBrowser(this.vPOSHacker._OpenPartialMarking_Link);

            _vFormBrowser.vFormSetScoringNo = lFSSN[i];
            _vFormBrowser.MainForm = this;

            ScoringNos[tmpCount - 1] = _vFormBrowser.vFormSetScoringNo.scoringNo;
            _vFormBrowser.Text = "作业窗口" + tmpCount + "(题号：" + ScoringNos[tmpCount - 1] + ")";//bug

            _vFormBrowser.formIndex = tmpCount;
            
            this.lFB.Add(_vFormBrowser);
           //this.lFB.Add( new FormBrowser(this.vPOSHacker._OpenPartialMarking_Link));
        }
        private void FormsGo() {


            //+init
            foreach(var tmpfb in this.lFB){
                tmpfb.RadioBtnsText();
            }


            //this.FormsCount = lFB.Count;
            this.BrowserWindowPosition = -1;
            this.CheckBoxAutoNext = false;//true;
            //-init
            this.ShowNextBrowserWindow();
            this.Hide();
        }


        private void MarkMultiWindows() {

            //FormBrowser _vFormBrowser;
            //int tmpCount = 1;
            //this.lFB = new List<FormBrowser>();
            lViewSelected = this.getDataGridViewSelected(false);
            
            //this.FormsCount = lViewSelected.Count;
            new Thread(new ThreadStart(CheckBrowser)).Start();


            return;
            //foreach (int i in lViewSelected) {

            //    if (tmpCount > this._MaxWindows)
            //        break;

            //    lFSSN[i].numberOfSet = this.textBox1.Text;
            //    lFSSN[i].mouseMarker = "2";

            //    _vFormBrowser = new FormBrowser(this.vPOSHacker._OpenPartialMarking_Link);

            //    _vFormBrowser.vFormSetScoringNo = lFSSN[i];
            //    _vFormBrowser.MainForm = this;

            //    _vFormBrowser.Text = "作业窗口" + tmpCount;//bug
            //    this.lFB.Add(_vFormBrowser);
            //    tmpCount++;
            
            //}

            //+init
            this.FormsCount = lFB.Count;
            this.BrowserWindowPosition = -1;
            this.CheckBoxAutoNext = false;//true;
            //-init
            this.ShowNextBrowserWindow();
            this.Hide();
        }



        private void MarkSingleWindow()
        {

            List<int> lViewSelected = this.getDataGridViewSelected(false);
            foreach (int i in lViewSelected)
            {

                lFSSN[i].numberOfSet = this.textBox1.Text;
                lFSSN[i].mouseMarker = "2";

                this.vFormBrowser.vFormSetScoringNo = lFSSN[i];

                this.vFormBrowser.MainForm.ScoringNos[this.vFormBrowser.formIndex - 1] = this.vFormBrowser.vFormSetScoringNo.scoringNo;
                this.vFormBrowser.Text = this.vFormBrowser.Text.Remove(this.vFormBrowser.Text.IndexOf("("));
                this.vFormBrowser.Text += "(题号：" + this.vFormBrowser.MainForm.ScoringNos[this.vFormBrowser.formIndex - 1] + ")";
                foreach (var tmpfb in this.vFormBrowser.MainForm.lFB)
                {
                    tmpfb.RadioBtnsText();
                }
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                this.Close();
                return;
            }


        }

        private void buttonMark_Click(object sender, EventArgs e)
        {
            //==Check this.textBox1.Text (1-100)
            try {
                int tmpNum =
                Convert.ToInt16(this.textBox1.Text);

                if (tmpNum > 100)
                    throw new SystemException();

            }catch(Exception){
                MessageBox.Show("抽取题目数量输入不正确！");
                return;
            }
            //
            this.Enabled = false;
            if (this.vFormBrowser == null)
                this.MarkMultiWindows();
            else
                this.MarkSingleWindow();
        }

        public void ShowNextBrowserWindow() {
            this.ShowNextBrowserWindow(this.BrowserWindowPosition+1);
        }

        public void ShowNextBrowserWindow(int position)
        {
            if (position >= this.FormsCount || position <0)
                position = 0;

            this.BrowserWindowPosition = position;
            for (int i = 0; i < this.FormsCount; i++)
            { 
                if(i == position)
                    this.lFB[i].Show();
                else
                    this.lFB[i].Hide();
            }            
        }

        private List<int> getDataGridViewSelected(bool onclick)
        {
            List<int> tmpList = new List<int>();
            object tmpValue;


            for (int i = 0; i < this.dataGridView1.RowCount; i++)
            {
                if (onclick)
                    tmpValue = this.dataGridView1[0, i].EditedFormattedValue;
                else
                    tmpValue = this.dataGridView1[0, i].Value;

                if (//true.Equals(this.dataGridView1[0, i].Value) || 
                    true.Equals(tmpValue))
                {
                        tmpList.Add(i);
                }
            }
            
            return tmpList;
        }

        private void buttonMarkEnable(bool onclick) {

            if (this.getDataGridViewSelected(onclick).Count == 0)
                this.buttonMark.Enabled = false;
            else
                this.buttonMark.Enabled = true;
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0 && e.RowIndex != -1)
            {
                if (true.Equals(this.dataGridView1[0, e.RowIndex].EditedFormattedValue))
                {
                    if(this.vFormBrowser != null){
                        for (int i = 0; i < this.dataGridView1.RowCount; i++)
                        {

                            if (i != e.RowIndex)
                            {
                                this.dataGridView1[0, i].Value = false;
                            }

                        }
                    }
                }
                this.buttonMarkEnable(true);
            }
        }

        private void FormPartrailQuestion_VisibleChanged(object sender, EventArgs e)
        {
            if(this.Visible)
                this.Init();
                        
        }

        private void FormPartrailQuestion_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (this.vParentForm != null)
            {
                this.vParentForm.Show();
            }
        }

        private bool isScoringNoActive(FormSetCourse SelectFormSetCourse,string scoringNo)
        {
            IList<MarkableQuestion> dbMarkableQuestions = new PartrailQuestionService().GetMarkableQuestions(SelectFormSetCourse.subjectCourseTestId, SelectFormSetCourse.pageNum);

            //Check Manage
            if (dbMarkableQuestions.Count == 0)
            {
                return true;
            }
            else
            {
                foreach (var dbMarkableQuestion in dbMarkableQuestions)
                {
                    if (scoringNo == dbMarkableQuestion.MarkID)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        public bool PermissionCheck(string ScoringNo)
        {
            FormSetCourse SelectFormSetCourse = Nissen_Common.ContextManager.Instance._FormSetCourse;

            if (!this.isScoringNoActive(SelectFormSetCourse, ScoringNo))
            {
                MessageBox.Show("该题目已被关闭，请重新选择！");
                return false;
            }


            if (!this.isCourseActive(SelectFormSetCourse))
                return false;

            if (!this.isTestActive(SelectFormSetCourse))
                return false;

            return true;
        }


    }
}
